package com.yang.interceptors;

import com.yang.utils.JwtUtil;
import com.yang.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 本类为拦截器相关功能类
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 前置拦截器方法
     * 当用户请求接口时，会先调用preHandle方法，根据验证传入的令牌和redis中的令牌是否一致判断是否放行。
     * 放行同时将数据存入线程
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            // 解析token
            Map<String, Object> claims = JwtUtil.parseToken(token);
            // 从redis中获取用户相关的token
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String tokenRedis = operations.get(claims.get("userId").toString());
            // 验证token是否有效
            if(tokenRedis == null){
                throw new Exception("token为空");
            }
            if(!tokenRedis.equals(token)){
                throw new Exception("token不一致");
            }
            //业务数据存入ThreadLocal
            ThreadLocalUtil.set(claims);
            return true;
        } catch (Exception e) {
            // Http状态码设置为401，并返回错误信息
            response.setStatus(401);
            return false;
        }
    }

    /**
     * 后置拦截器方法
     * 当用户的相关操作执行完毕后，清除相关数据
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 业务数据从ThreadLocal中移除
        ThreadLocalUtil.remove();
    }
}
